package com.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: pzj
 * \* Date: 2021/10/11
 * \* Time: 18:50
 * \* Description:
 * \
 */
public class BIOServer {
    public static void main(String[] args) throws Exception {
        //线程池机制

        //1、创建一个线程池
        ExecutorService pool = Executors.newCachedThreadPool();
        //2、如果有客户端连接，就创建一个线程，与之通信
        //创建ServerSocket
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了。。。。");

        while (true){
            //监听，等待客户端连接，如果没有客户端连接来，线程就会阻塞在这里
            final Socket socket = serverSocket.accept();
            System.out.println("有一个客户端连接到服务器。。。");

            pool.execute(new Runnable() {
                @Override
                public void run() {
                    //与客户端通信
                    handler(socket);
                }
            });
        }


    }

    //编写一个handler方法，与客户端通信
    public static void handler(Socket socket){
        byte[] bytes = new byte[1024];
        //通过socket获取输入流
        try {
            InputStream inputStream = socket.getInputStream();
            //循环读取客户端发送的数据
            int read;
            //如果没有数据过来，那么这里的read方法会阻塞
            while ((read = inputStream.read(bytes))!=-1){
                    System.out.println(new String(bytes,0,read));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            System.out.println("关闭客户端连接。。。");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}